// Stripe Webhook 处理订阅成功事件
// 部署到 Vercel 时需要配置为 serverless function

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;

    const sig = req.headers['stripe-signature'];
    let event;

    try {
      event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
    } catch (err) {
      console.error('Webhook signature verification failed:', err.message);
      return res.status(400).send(`Webhook Error: ${err.message}`);
    }

    // 处理订阅成功事件
    switch (event.type) {
      case 'checkout.session.completed':
        const session = event.data.object;
        
        // 这里可以更新数据库中的用户订阅状态
        // 例如：将用户的 subscription_status 设置为 'active'
        // 设置订阅到期时间等
        
        console.log('Subscription created:', session.id);
        break;

      case 'customer.subscription.updated':
        const subscription = event.data.object;
        
        // 处理订阅更新（续费、升级等）
        console.log('Subscription updated:', subscription.id);
        break;

      case 'customer.subscription.deleted':
        const deletedSubscription = event.data.object;
        
        // 处理订阅取消
        console.log('Subscription cancelled:', deletedSubscription.id);
        break;

      default:
        console.log(`Unhandled event type: ${event.type}`);
    }

    res.status(200).json({ received: true });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).json({ error: 'Webhook processing failed' });
  }
}